const app = getApp()
Page({
  data: {
    unLogin:false,
    btnDisabled: false,
    isLoading: false,
    currentIndex: 0,
    isLocked: false,
    page: 1,
    size: 10,
    hasNext: true,
    orders: [

    ]
  },
  onShow() {
    this.setData({
      unLogin:false
    })
    this.setData(
      {
        page: 1,
        size: 10,
      }
    )
    this.initData()
  },
  initData() {
    let param = {}
    param.page = this.data.page
    param.size = this.data.size
    let _this = this
    app.order.getSendOrder(param).then(res => {
      console.log(32323)
      console.log(res.code)
      if (res.code == 200) {
        _this.setData({
          'orders': res.data.rescueOrderResponses,
          'hasNext': res.data.hasNext
        })
      } else if (res.code == 10000) {
        _this.setData({
          unLogin:true
        })
      }
    })
  },
  onLoad() {
    this.setInterval = setInterval(() => {
      this.setData({ refresh: Date.now() }) // 触发视图更新
    }, 1000)
  },
  goDetail: function (e) {
    console.log(e.currentTarget.dataset.orderno)
    let orderno = e.currentTarget.dataset.orderno
    wx.navigateTo({
      url: "/pages/tasks/details/details?orderno=" + orderno,
    })
    console.log('按钮被点击', e.currentTarget.dataset);
  },
  loadMoreOrders() {
    let hasNext = this.data.hasNext
    if (hasNext) {
      let param = {}
      param.page = this.data.page + 1
      this.setData({
        page: param.page
      })
      param.size = this.data.size
      let _this = this
      console.log(222)
      app.order.getSendOrder(param).then(res => {
        if (res.code == 200) {
          let orders = _this.data.orders.concat(res.data.rescueOrderResponses)
          _this.setData({
            orders,
            'hasNext': res.data.hasNext
          })
        }
      })
    }
    console.log(21212)
  },
  handlePay: function (e) {
    const id = e.currentTarget.dataset.id;
    let params = {}
    this.setData({
      btnDisabled: true
    })
    setTimeout(() => {
      this.setData({
        btnDisabled: false
      })
    }, 2000);
    params.orderId = id
    let _this = this
    app.task.getPaySettings(params).then(res => {
      if (res.code == 200) {
        _this.setData({
          btnDisabled: false
        })
        wx.requestPayment({
          timeStamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          package: res.data.package,
          signType: 'MD5',
          paySign: res.data.paySign,
          success(res) {
            // wx.switchTab({
            //   url: '../tasks/tasks',
            // })
          },
          fail(err) {
          }
        })
      }
    })
  },
  compareTime(expireTime) {
    console.log(32323)
    if (!expireTime) return false
    return new Date(expireTime) > new Date()
  },
  cancelOrder: function (e) {
    const id = e.currentTarget.dataset.id;
    let params = {}
    params.id = id
    let _this = this
    wx.showModal({
      title: '确认取消',
      content: '确定要取消这个订单吗？',
      success: (res) => {
        if (res.confirm) {
          app.task.cancelOrder(params).then(res => {
            if (res.code == 200) {
              let orders = _this.data.orders
              orders.forEach(item => {
                console.log(item)
                if (id === item.id) {
                  if (item.status === -1) {
                    item.status = 8
                  } else {
                    item.status = 6
                  }
                }
                _this.setData({
                  orders
                })
              });
            }
          })
        }
      }
    });
  },
  // Swiper滑动切换事件
  onSwiperChange: function (e) {
    console.log(21221)
    const newIndex = e.detail.current;
    const oldIndex = this.data.currentIndex;

    // 防止快速滑动导致的重复触发
    if (newIndex === oldIndex) return;

    this.setData({
      currentIndex: newIndex
    });

    // 滑动到最后一页时加载更多数据
    if (newIndex === this.data.item.commodityResponses.length - 1) {
      this.loadMoreData();
    }

    // 特定条件下锁定滑动（如弹窗出现时）
    if (newIndex === 2) { // 示例条件
      this.setData({ isLocked: true });
    } else {
      this.setData({ isLocked: false });
    }
  },

  // 加载更多数据方法
  loadMoreData: function () {
    wx.showLoading({ title: '加载中...' });
    // 模拟异步请求
    setTimeout(() => {
      const newItems = [...this.data.item.commodityResponses, ...new Array(5).fill().map((_, i) => ({
        id: Date.now() + i,
        name: `商品${i + 1}`,
        price: (Math.random() * 100).toFixed(2)
      }))];

      this.setData({
        'item.commodityResponses': newItems
      });
      wx.hideLoading();
    }, 1000);
  },
  confirmReceipt: function (e) {
    let _this = this
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确认收货',
      content: '请确认已收到货物',
      success: (res) => {
        if (res.confirm) {
          let params = {}
          params.orderId = id
          params.orderStatus = 4
          app.order.updateStatus(params).then(res => {
            if (res.code == 200) {
              let orders = _this.data.orders
              orders.forEach(item => {
                console.log(item)
                if (id === item.id) {
                  item.status = 4
                }
                _this.setData({
                  orders
                })
              })
            }
          })
          // this.updateOrderStatus(id, 'completed', '已完成');
        }
      }
    });
  },
  gotoHome() {
    wx.switchTab({
      url: '../goods/goods',
    })
  },
  gotoLogin() {
    wx.navigateTo({
      url: '/pages/index/index',
    })
  },
  updateOrderStatus: function (id, status, statusText) {
    const orders = this.data.orders.map(item => {
      if (item.id === id) {
        return { ...item, status, statusText };
      }
      return item;
    });

    this.setData({ orders });
    wx.showToast({
      title: '操作成功',
      icon: 'success'
    });
  }
});
